package main

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"log"
	"net/http"
)

var db *sql.DB

func getDb() {
	// 数据库连接字符串
	dsn := "root:root@tcp(mysql:3306)/itianyu"

	// 打开数据库连接
	var err error
	db, err = sql.Open("mysql", dsn)
	if err != nil {
		log.Fatalf("Error opening database: %v", err)
	}

	// 验证数据库连接
	err = db.Ping()
	if err != nil {
		log.Fatalf("Error verifying connection to the database: %v", err)
	}
}

func AHandler(w http.ResponseWriter, r *http.Request) {
	getDb()
	rows, err := db.Query("SELECT id FROM test")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer rows.Close()

	var users []int
	for rows.Next() {
		var id int
		if err := rows.Scan(&id); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		users = append(users, id)
	}

	if err := rows.Err(); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	for _, user := range users {
		fmt.Fprintf(w, "%d", user)
	}
}

func main() {
	http.HandleFunc("/", AHandler)
	http.ListenAndServe("0.0.0.0:8080", nil)
}
